package cz.muni.fi.pa165.sportclubmanager.dao;

/**
 *
 * @author xondrusk
 */

import cz.muni.fi.pa165.sportclubmanager.entity.AgeCategory;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

@Repository
public class AgeCategoryDAOImpl implements AgeCategoryDAO {
    
    @PersistenceContext
    private EntityManager em;
    
    public AgeCategoryDAOImpl() {
    }

    @Override
    public void create(AgeCategory ac) {
        if(ac == null || ac.getName() == null || ac.getAgeFrom() > ac.getAgeTo() || ac.getId() != null ||
                ac.getName().length() > 255 || ac.getAgeFrom() < 0){
            throw new IllegalArgumentException();
        }
        em.persist(ac);
    }

    @Override
    public void update(AgeCategory ac) {
        if(ac == null || ac.getId() == null || ac.getName() == null || ac.getAgeFrom() > ac.getAgeTo() ||
                ac.getName().length() > 255 || ac.getAgeFrom() < 0){
            throw new IllegalArgumentException();
        }
        em.merge(ac);
    }

    @Override
    public void remove(AgeCategory ac) {
        if(ac == null || ac.getId() == null){
            throw new IllegalArgumentException();
        }
        ac = em.merge(ac);
        em.remove(ac);
    }

    @Override
    public AgeCategory find(Long id) {
        if(id == null || id < 0){
            throw new IllegalArgumentException();
        }
        AgeCategory ageCategory = em.find(AgeCategory.class, id);
        return ageCategory;
    }

    
    @Override
    public AgeCategory findClosestLower(Long id) {
        if(id == null || id < 0){
            throw new IllegalArgumentException();
        }
        
        AgeCategory previous = null;
        boolean found = false;

        // get list sorted in ascending order of age intervals
        TypedQuery<AgeCategory> query = em.createQuery("SELECT a FROM AgeCategory a ORDER BY a.ageFrom, a.ageTo",AgeCategory.class);
        List<AgeCategory> findAll = query.getResultList();
        
        for (AgeCategory ageCategory : findAll) {
            if (ageCategory.getId().equals(id)) {
                found = true;
                break;
            }
            previous = ageCategory;
        }

        return found ? previous : null;
    }
    
    
    @Override
    public List<AgeCategory> findAll() {
        Query query = em.createQuery("SELECT a FROM AgeCategory a");
        List<AgeCategory> ageCategories = (List<AgeCategory>) query.getResultList();
        return ageCategories;
    }
}
